﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using NPOI.SS.Formula.Functions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CoreShop.App
{
    public partial class frmCustomerDisplay : UIForm
    {
        static System.Timers.Timer timer_data = null;
        /// <summary>
        /// 图片文件夹
        /// </summary>
        public List<Image> imgList
        {
            get;
            set;
        }
        public frmCustomerDisplay()
        {
            InitializeComponent();
            this.imgList = new List<Image>();
            if (timer_data == null)
            {
                timer_data = new System.Timers.Timer();
                timer_data.Interval = 1000 * AppConstVars.systemsetup.SecondScreemTime;
                timer_data.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
                timer_data.Enabled = true;
            }
            this.gridPos.RectColor = Color.Gainsboro;
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                timer_data.Enabled = false;
                SetScreemImgShow();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                timer_data.Enabled = true;
            }
        }

        /// <summary>
        /// 遍历文件夹内文件
        /// </summary>
        /// <param name="path"></param>
        public void ListImgsInDirectory()
        {
            string path = AppConstVars.SecondScreemImg;
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            DirectoryInfo directoryInfo = new DirectoryInfo(path);
            Image img = null;

            if (imgList != null) this.imgList.Clear();
            var imgDataList = new corecmsscreenimgService().GetList();
            foreach (FileInfo file in directoryInfo.GetFiles())
            {
                if (string.Compare(file.Extension, ".jpg", true) == 0 ||
                    string.Compare(file.Extension, ".jpeg", true) == 0 ||
                    string.Compare(file.Extension, ".png", true) == 0 ||
                    string.Compare(file.Extension, ".bmp", true) == 0)
                {
                    string aFirstName = file.FullName.Substring(file.FullName.LastIndexOf("\\") + 1, (file.FullName.LastIndexOf(".") - file.FullName.LastIndexOf("\\") - 1));
                    var imgDataRow = imgDataList.Find(p => p.tenantScreenImgId == CommFunc.ConvertToBigInt(aFirstName));
                    if ((aFirstName != null) && (imgDataRow != null))
                    {
                        img = Image.FromFile(file.FullName);
                        this.imgList.Add(img);
                    }
                }
            }
            if (this.imgList != null && this.imgList.Count == 0)
            {
                img = Properties.Resources._default;
                this.imgList.Add(img);
            }
            if (this.imgList != null && this.imgList.Count > 0)
            {
                img = this.imgList[0];
                pic_GoodImg.SizeMode = PictureBoxSizeMode.StretchImage;
                pic_GoodImg.Image = img;
            }
        }

        Int32 ImgIndex = 0;
        private void SetScreemImgShow()
        {
            if (!pic_GoodImg.IsHandleCreated) return;

            this.Invoke(new Action(() =>
            {
                try
                {
                    if (this.imgList != null && this.imgList.Count > 0)
                    {
                        Image img;
                        if (ImgIndex >= this.imgList.Count) ImgIndex = 0;
                        img = this.imgList[ImgIndex++];
                        pic_GoodImg.SizeMode = PictureBoxSizeMode.StretchImage;
                        pic_GoodImg.Image = img;
                        pic_GoodImg.Visible = true;
                    }
                }
                catch (Exception ex)
                {
                    //Log.LogManage.Error("切换副屏广告错误！" + ex);
                }
            }));
        }

        public void SetCustShowInfo(bool isCash)
        {
            try
            {
                if ((!isCash) || (Program.frmOrdering.orderingMember == null))
                {
                    pnl_MemberAmt.Visible = false;
                    pnlDataFooter.Height = 112;
                    lbl_MemberName.Text = "您好!欢迎光临.";
                    lbl_MemberAmt.Text = "¥0";
                    lbl_MemberInt.Text = "0";
                }
                else
                {

                    pnlDataFooter.Height = 210;
                    pnl_MemberAmt.Visible = true;
                    lbl_MemberName.Text = "您好!" + Program.frmOrdering.orderingMember.userName;
                    lbl_MemberAmt.Text = "¥" + CommFunc.ConvertToDecimal(Program.frmOrdering.orderingMember.balance).ToString("#0.00");
                    lbl_MemberInt.Text = CommFunc.ConvertToInt32(Program.frmOrdering.orderingMember.point).ToString();
                }
                if ((Program.frmOrdering.orderingSelected != null) && (Program.frmOrdering.orderingDetail != null))
                {
                    isCash = true;
                    //var mRowActive = Program.frmOrdering.orderingDetail.Find(p => p.id == Program.frmOrdering.orderingSelected.id);
                    //if (mRowActive != null)
                    //{
                    //    mRowActive.quantity = Program.frmOrdering.orderingSelected.quantity;
                    //    mRowActive.realPrice = Program.frmOrdering.orderingSelected.realPrice;
                    //    mRowActive.allAmount = Program.frmOrdering.orderingSelected.allAmount;
                    //}
                }
                else
                {
                    isCash = false;
                    this.pic_GoodImg.Visible = false;
                }
                this.binDetail.DataSource = null;
                this.binDetail.DataSource = Program.frmOrdering.orderingDetail;
                this.gridPos.DataSource = this.binDetail;
                this.gridPos.Refresh();
                if (this.binDetail.Count > 0)
                {
                    this.gridPos.FirstDisplayedScrollingRowIndex = this.binDetail.Count - 1;
                }
                this.lblDataSum.Text = Program.frmOrdering.lblAllAmount.Text;
                if (isCash)//点餐时
                {
                    timer_data.Enabled = false;
                    SetGoodsImgShow();
                }
                else
                {
                    timer_data.Enabled = true;
                    timer_data.Start();
                }
            }
            catch (Exception ex) { }
        }

        //轮询访问广告数据
        private void frmCustomerDisplay_Load(object sender, EventArgs e)
        {
            //访问广告业参数
            gridPos.AutoGenerateColumns = false;
            int sHideOrder = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "HideOrder"));
            if (sHideOrder == 1) pnlData.Visible = false;
            int sAutoLayout = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "AutoLayout"));
            if (sAutoLayout == 1 && Screen.AllScreens.Count() > 1)
            {
                this.ShowTitle = false;
                //this.ShowFullScreen = true;
                int ScreenH = Screen.PrimaryScreen.Bounds.Height;
                int ScreenW = Screen.PrimaryScreen.Bounds.Width;
                Screen s2 = Screen.AllScreens[1];
                Rectangle r2 = s2.WorkingArea;
                this.Left = r2.Left; //Screen.PrimaryScreen.Bounds.Width;
                this.Top = r2.Top;
                this.Height = r2.Height;
                this.Width = r2.Width;
            }
            else
            {
                this.Left = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "FormLeft"));
                this.Top = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "FormTop"));
                this.Height = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "FormHeight"));
                this.Width = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "FormWidth"));
            }
            ListImgsInDirectory();
            try
            {

                //AppConstVars.sAdvGoodImg = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "AdvGoodImg"));
                //if (AppConstVars.sAdvUrlShop != "")
                //{
                //    WebBrowser browser = new WebBrowser();
                //    browser.ScriptErrorsSuppressed = true;
                //    browser.Dock = DockStyle.Fill;
                //    this.pnl_AdvUrl.Controls.Add(browser);
                //    browser.Navigate(AppConstVars.sAdvUrlShop);
                //}
            }
            catch { }
            pic_GoodImg.Visible = false;
            SetCustShowInfo(false);
        }

        /// <summary>
        /// 设置广告轮播时间(秒)
        /// </summary>
        public void SetAdvertisingTime(object time)
        {
            timer_data.Interval = ((int)time * 1000);
        }

        private void picFooter_DoubleClick(object sender, EventArgs e)
        {

        }

        private void SetGoodsImgShow()
        {
            if (!AppConstVars.systemsetup.showFoodImgCust) return;
            try
            {
                if (Program.frmOrdering.orderingSelected != null)
                {
                    if (string.IsNullOrEmpty(Program.frmOrdering.orderingSelected.foodImage))
                    {
                        var foodModel = new corecmsfoodServices().GetById(Program.frmOrdering.orderingSelected.foodId);
                        if (foodModel != null)
                            Program.frmOrdering.orderingSelected.foodImage = foodModel.image;
                    }
                    if (!string.IsNullOrEmpty(Program.frmOrdering.orderingSelected.foodImage))
                    {
                        var foodImage = Program.frmOrdering.orderingSelected.foodImage;
                        string sImageFile = new FoodUtil().GetProductImageFile(foodImage);
                        if ((sImageFile != null) && File.Exists(sImageFile))
                        {
                            pic_GoodImg.Image = Image.FromFile(sImageFile);
                            pic_GoodImg.Visible = true;
                        }
                        else pic_GoodImg.Visible = false;
                    }
                }
            }
            catch
            {
            }
        }

        private void gridPos_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            //if (e.RowIndex == -1)
            //{
            //    Graphics gpcEventArgs = e.Graphics;
            //    Color clrFore = Color.White;
            //    Color clrBack = Color.FromArgb(92, 46, 75);
            //    Font fntText = e.CellStyle.Font;

            //    FontFamily mFontf = new FontFamily("宋体");
            //    Font mFontName = new Font(mFontf, 12, FontStyle.Bold);

            //    string strValue = CommFunc.ConvertToString(e.Value);
            //    Size sizText = TextRenderer.MeasureText(e.Graphics, strValue, mFontName);

            //    int intX = e.CellBounds.Left + e.CellStyle.Padding.Left;
            //    int intY = e.CellBounds.Top + e.CellStyle.Padding.Top + 7;
            //    int intWidth = e.CellBounds.Width - (e.CellStyle.Padding.Left + e.CellStyle.Padding.Right);
            //    int intHeight = sizText.Height + (e.CellStyle.Padding.Top + e.CellStyle.Padding.Bottom);

            //    gpcEventArgs.FillRectangle(new SolidBrush(clrBack), e.CellBounds);

            //    if (e.ColumnIndex > 0)
            //    {
            //        TextRenderer.DrawText(e.Graphics, strValue, mFontName, new Rectangle(intX, intY, intWidth, intHeight), clrFore,
            //            TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis | TextFormatFlags.Right);
            //    }
            //    e.Handled = true;
            //}
        }

        private void gridPos_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (AppConstVars.systemsetup.orderSetType != 1) SetGoodsImgShow();
        }

        private void lbl_MemberName_DoubleClick(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void pic_GoodImg_DoubleClick(object sender, EventArgs e)
        {
            this.Hide();
        }
    }
}
